package cn.chencq.gdt.vo;

import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.gdt.banner.GdtBaner;
import cn.chencq.gdt.utils.Utils;

public class Bussiness implements Callable<Boolean> {
	private static final Logger logger = LoggerFactory.getLogger(Bussiness.class);
	private String rid;
	private Gdt gdt;
	private ProxyIp proxy;
	private Mobile mobile;

	public Bussiness() {
		super();
	}

	public Bussiness(String rid, Gdt gdt, ProxyIp proxy, Mobile mobile) {
		super();
		this.rid = rid;
		this.gdt = gdt;
		this.proxy = proxy;
		this.mobile = mobile;
	}

	@Override
	public Boolean call() throws Exception {
		boolean result = true;
		int random = Utils.getNum(0, 10000);
		BanerAd ad = null;
		try {
			// 确保请求广告成功,重试3次失败,终止运行
			int retry = 0;
			do {
				ad = GdtBaner.queryAd(rid, gdt, proxy, mobile);
				if (retry > 3) {
					throw new RuntimeException("请求广告异常");
				}
				retry++;
			} while (ad == null);

			if (random <= 9000) {// 曝光
				boolean ret = GdtBaner.display(rid, ad, proxy, mobile);
				if (ret && random <= 100) {// 点击
					GdtBaner.click(rid, ad, proxy, mobile);
				}
			}
		} catch (RuntimeException ex) {
			result = false;
			logger.info("rid:{},bussiness throw exception:{}", rid, ex);
		}
		return result;
	}
}